<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>订单列表</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link href="{__STATIC__}/layuiAdmin/layui/css/layui.css" rel="stylesheet">
	<link href="{__STATIC__}/layuiAdmin/adminui/dist/css/admin.css" rel="stylesheet">
	<link href="{__STATIC__}/layuiAdmin/style/style.css" rel="stylesheet">
</head>
<body>
	<div class="layui-fluid">
		<div class="layui-card">
			<div class="layui-card-body">
				<div style="padding-bottom: 10px;">
					<button class="layui-btn layui-btn-normal btn-top" data-type="batchDel">批量删除</button>
					<button class="layui-btn layui-btn-info btn-top" data-type="export">导出订单</button>
					<div class="layui-form search_ctr">
						<div class="layui-form-item">
							<div class="layui-inline">
								<div class="layui-input-inline w160">
									<input type="text" name="k3" id="k3" class="layui-input" placeholder="开始时间" autocomplete="off" value="">
								</div>
								<div class="layui-form-mid layui-word-aux">-</div>
								<div class="layui-input-inline w160">
									<input type="text" name="k4" id="k4" class="layui-input" placeholder="结束时间" autocomplete="off" value="">
								</div>
								<div class="layui-input-inline w120">
									<select name="k5">
										<option value="">订单类型</option>
										<option value="normal">普通订单</option>
										<option value="activity">促销订单</option>
										<option value="seckill">秒杀订单</option>
										<option value="assist">助力订单</option>
										<option value="combination">拼团订单</option>
										<option value="integral">积分订单</option>
										<option value="raffle">抽奖订单</option>
									</select>
								</div>
								<div class="layui-input-inline w120">
									<select name="k2">
										<option value="">订单状态</option>
										<option value="1">待付款</option>
										<option value="2">待发货</option>
										<option value="3">待收货</option>
										<option value="4">已完成</option>
										<option value="-1">已取消</option>
									</select>
								</div>
								<div class="layui-input-inline w200">
									<input type="text" name="keys" placeholder="输入订单号或收货人查询" class="layui-input">
								</div>
								<button class="layui-btn layui-btn-normal" lay-submit lay-filter="LAY-search">查询</button>
							</div>
						</div>
					</div>
				</div>

				<table id="LAY-table" lay-filter="LAY-table"></table>
				<script type="text/html" id="name">
					{{d.name}}，{{d.tel}}
				</script>
				<script type="text/html" id="info">
					{{#  layui.each(d.goods, function(index, item){ }}
					<div class="order_goods_ctr">
						<div class="order_goods_pic">
							<img src="{{= item.pic}}">
						</div>
						<div class="order_goods_right">
							<div class="order_goods_title">{{= item.title}}</div>
							<div class="order_goods_spec">{{= item.spec_key_name}}×{{= item.amount}}</div>
						</div>
					</div>
					{{#  }); }}
				</script>
				<script type="text/html" id="state">
					{{d.order_state}}
					{{#  if(d.order_state_no > 1 && d.refund_state > 0){ }}
					<span class="layui-red"><br>退款中</span>
					{{#  } }}
				</script>
				<script type="text/html" id="tableBar">
					<a class="link-text" lay-event="edit">查看</a>
					<div class="link-line"></div>
					<a class="link-text" lay-event="opt">更多</a>
				</script>

			</div>
		</div>
	</div>
</body>
</html>
<script src="{__STATIC__}/sheetjs/xlsx.core.min.js"></script>
<script src="{__STATIC__}/layuiAdmin/layui/layui.js"></script>
<script>
	layui.config({
		base: '{__STATIC__}/layuiAdmin/' // 静态资源所在路径
	}).use(['index', 'layer', 'table', 'form', 'laydate', 'dropdown'], function(){
		let $ = layui.$;
		let layer = layui.layer;
		let table = layui.table;
		let form = layui.form;
		let laydate = layui.laydate;
		let dropdown = layui.dropdown;

		//搜索日期
		laydate.render({
			elem: '#k3'
			,type: 'datetime'
			,trigger: 'click'
		});

		laydate.render({
			elem: '#k4'
			,type: 'datetime'
			,trigger: 'click'
		});

		//初始化列表
		table.render({
			elem: '#LAY-table'
			,url: "{:url('getList')}"
			,cols: [[
				{type: 'checkbox', fixed: 'left'}
				,{field: 'id', width: 80, title: 'ID', sort: true}
				,{field: 'order_sn', width: 180, title: '订单号'}
				,{field: 'title', minWidth:280, title: '商品信息', templet: '#info'}
				,{field: 'name', width: 200, title: '收货人', templet: '#name'}
				,{field: 'pay_price', width: 110, title: '实付款'}
				,{field: 'pay_type', width: 100, title: '支付方式', align:'center'}
				,{field: 'order_state', width: 100, title: '订单状态', align:'center', templet: '#state'}
				,{field: 'order_type_title', width: 100, title: '订单类型', align:'center'}
				,{field: 'add_date', width: 180, title: '下单时间'}
				,{title: '操作', width: 106, align:'center', fixed: 'right', toolbar: '#tableBar'}
			]]
			,page: true
			,limit: 20
			,height: 'full-100'
			,lineStyle: 'height: 94px;'
			,text: {none: '暂无相关数据'}
		});

		//监听搜索
		form.on('submit(LAY-search)', function(data){
			let field = data.field;
			//执行重载
			table.reload('LAY-table', {
				url: "{:url('getList')}"
				,where: field
				,page: {
					curr: 1 //重新从第 1 页开始
				}
			});
		});

		//表格内操作按钮
		table.on('tool(LAY-table)', function(obj){
			let tableData = obj.data;
			if(obj.event === 'edit'){
				layer.open({
					type: 2
					,title: '订单详情'
					,content: "{:url('edit')}?id=" + tableData.id
					,maxmin: false
					,area: ['90%', '90%']
				});
			} else if(obj.event === 'opt'){
				// 更多下拉菜单
				let data = [];
				if(tableData.order_state_no == -1) {
					//已取消
					data = [
						{
							title: '删除订单',
							id: 'del'
						}
					];
				}
				if(tableData.order_state_no == 1) {
					//待付款
					data = [
						{
							title: '取消订单',
							id: 'cancel'
						},
						{
							title: '调整价格',
							id: 'editPrice'
						},
						{
							title: '订单备注',
							id: 'info'
						}
					];
				}
				if(tableData.order_state_no == 2) {
					//待发货
					data = [
						{
							title: '订单发货',
							id: 'sendGoods'
						},
						{
							title: '打配货单',
							id: 'printOrder'
						},
						{
							title: '订单备注',
							id: 'info'
						}
					];
				}
				if(tableData.order_state_no == 3) {
					//待收货
					data = [
						{
							title: '确认收货',
							id: 'receipt'
						},
						{
							title: '打配货单',
							id: 'printOrder'
						},
						{
							title: '订单备注',
							id: 'info'
						}
					];
					if(tableData.pay_type == '货到付款' && tableData.pay_date == '') {
						data.unshift({
							title: '确认收款',
							id: 'setPay'
						});
					}
				}
				if(tableData.order_state_no == 4) {
					//已完成
					data = [
						{
							title: '打配货单',
							id: 'printOrder'
						},
						{
							title: '订单备注',
							id: 'info'
						}
					];
					if(tableData.pay_type == '货到付款' && tableData.pay_date == '') {
						data.unshift({
							title: '确认收款',
							id: 'setPay'
						});
					}
				}
				dropdown.render({
					elem: this,
					show: true, // 外部事件触发即显示
					data: data,
					click: function(data){
						//根据 id 做出不同操作
						if(data.id === 'cancel'){
							layer.confirm('确定要取消吗？', function(){
								$.ajax({
									type:"post",
									url:"{:url('cancel')}",
									data: {
										m_id:tableData.id
									},
									dataType:"json",
									beforeSend: function () {
										layer.load(1);
									},
									success:function(res){
										layer.closeAll();
										if(res.code == 0){
											if(res.msg == 'success') {
												layer.msg('取消成功', {
													time: 1500
												}, function(){
													table.reloadData('LAY-table',{},true); //数据刷新
												});
											} else {
												layer.msg(res.msg);
											}
										} else {
											layer.msg(res.msg);
										}
									}
								});
							});
						}
						if(data.id === 'del'){
							layer.confirm('确定要删除吗？', function(){
								$.ajax({
									type:"post",
									url:"{:url('delete')}",
									data: {
										m_id:tableData.id
									},
									dataType:"json",
									beforeSend: function () {
										layer.load(1);
									},
									success:function(res){
										layer.closeAll();
										if(res.code == 0){
											if(res.msg == 'success') {
												obj.del();
												layer.msg('删除成功');
											} else {
												layer.msg(res.msg);
											}
										}
										else {
											layer.msg(res.msg);
										}
									}
								});
							});
						}
						if(data.id === 'editPrice'){
							layer.open({
								type: 2
								,title: '价格调整'
								,content: "{:url('editPrice')}?id=" + tableData.id
								,maxmin: false
								,area: ['500px', '280px']
								,btn: ['确定', '取消']
								,yes: function(index, layero){
									let iframeWindow = window['layui-layer-iframe'+ index];
									let submitID = 'LAY-submit';
									let submit = layero.find('iframe').contents().find('#'+ submitID);

									//监听提交
									iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
										let field = data.field; //获取提交的字段
										$.ajax({
											type:"post",
											url:"{:url('savePrice')}",
											data: {
												m_express_price:field.m_express_price,
												m_trim_price:field.m_trim_price,
												m_id:field.m_id
											},
											dataType:"json",
											beforeSend: function () {
												layer.load(1);
											},
											success:function(res){
												layer.closeAll();
												if(res.code == 0){
													table.reloadData('LAY-table',{},true); //数据刷新
												}
												else {
													layer.msg(res.msg);
												}
											}
										});
									});
									submit.trigger('click');
								}
							});
						}
						if(data.id === 'info'){
							layer.open({
								type: 2
								,title: '订单备注'
								,content: "{:url('editInfo')}?id=" + tableData.id
								,maxmin: false
								,area: ['500px', '280px']
								,btn: ['确定', '取消']
								,yes: function(index, layero){
									let iframeWindow = window['layui-layer-iframe'+ index];
									let submitID = 'LAY-submit';
									let submit = layero.find('iframe').contents().find('#'+ submitID);

									//监听提交
									iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
										let field = data.field; //获取提交的字段
										$.ajax({
											type:"post",
											url:"{:url('saveInfo')}",
											data: {
												m_info:field.m_info,
												m_id:field.m_id
											},
											dataType:"json",
											beforeSend: function () {
												layer.load(1);
											},
											success:function(res){
												layer.closeAll();
												if(res.code == 0){
													layer.msg('备注成功');
												}
												else {
													layer.msg(res.msg);
												}
											}
										});
									});
									submit.trigger('click');
								}
							});
						}
						if(data.id === 'sendGoods'){
							layer.open({
								type: 2
								,title: '订单发货'
								,content: "{:url('sendGoods')}?id=" + tableData.id
								,maxmin: false
								,area: ['500px', '448px']
								,btn: ['确定', '取消']
								,yes: function(index, layero){
									let iframeWindow = window['layui-layer-iframe'+ index];
									let submitID = 'LAY-submit';
									let submit = layero.find('iframe').contents().find('#'+ submitID);

									//监听提交
									iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
										let field = data.field; //获取提交的字段
										$.ajax({
											type:"post",
											url:"{:url('saveSend')}",
											data: {
												m_express_type:field.m_type,
												m_express_title:field.m_express_title,
												m_express_sn:field.m_express_sn,
												m_express_info:field.m_express_info,
												m_id:field.m_id
											},
											dataType:"json",
											beforeSend: function () {
												layer.load(1);
											},
											success:function(res){
												layer.closeAll();
												if(res.code == 0){
													table.reloadData('LAY-table',{},true); //数据刷新
												}
												else {
													layer.msg(res.msg);
												}
											}
										});
									});
									submit.trigger('click');
								}
							});
						}
						if(data.id === 'receipt'){
							layer.confirm('确定要收货吗？', function(){
								$.ajax({
									type:"post",
									url:"{:url('receipt')}",
									data: {
										m_id:tableData.id
									},
									dataType:"json",
									beforeSend: function () {
										layer.load(1);
									},
									success:function(res){
										layer.closeAll();
										if(res.code == 0){
											table.reloadData('LAY-table',{},true); //数据刷新
										} else {
											layer.msg(res.msg);
										}
									}
								});
							});
						}
						if(data.id === 'printOrder'){
							window.open("{:url('printOrder')}?id=" + tableData.id);
						}
						if(data.id === 'setPay'){
							layer.confirm('确定收款吗？', function(){
								$.ajax({
									type:"post",
									url:"{:url('savePay')}",
									data: {
										m_id:tableData.id
									},
									dataType:"json",
									beforeSend: function () {
										layer.load(1);
									},
									success:function(res){
										layer.closeAll();
										if(res.code == 0){
											table.reloadData('LAY-table',{},true); //数据刷新
										} else {
											layer.msg(res.msg);
										}
									}
								});
							});
						}
					},
					align: 'right', // 右对齐弹出
					style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);', //设置额外样式
					className: 'order_dropdown'
				})
			}
		});

		//头部操作按钮
		$('.btn-top').on('click', function(){
			let type = $(this).data('type');
			active[type] ? active[type].call(this) : '';
		});

		let active = {
			batchDel: function(){
				let checkStatus = table.checkStatus('LAY-table');
				let checkData = checkStatus.data //得到选中的数据
				let ids = "0";
				if(checkData.length === 0){
					return layer.msg('请选择数据');
				}
				$.each(checkData,function(key,value){
					ids = ids + "," + checkData[key]['id'];
				});
				layer.confirm('确定要删除吗？', function(index) {
					$.ajax({
						type:"post",
						url:"{:url('delete')}",
						data: {
							m_id:ids
						},
						dataType:"json",
						beforeSend: function () {
							layer.load(1);
						},
						success:function(res){
							layer.closeAll();
							if(res.code == 0){
								let msg = res.msg == 'success' ? '删除成功' : res.msg;
								layer.msg(msg, {
									time: 2000
								}, function(){
									table.reloadData('LAY-table',{},true); //数据刷新
								});
							}
							else {
								layer.msg(res.msg);
							}
						}
					});
				});
			}
			,export: function(){
				let checkStatus = table.checkStatus('LAY-table')
				let checkData = checkStatus.data //得到选中的数据
				let str = "确定导出选中数据吗？";
				let ids = "0";
				$.each(checkData,function(key,value){
					ids = ids + "," + checkData[key]['id'];
				});
				if(checkData.length === 0){
					str = "未选择数据将导出当前所有，确定导出吗？";
				}
				layer.confirm(str, function(index) {
					layer.closeAll();
					// 要打印的数据格式 对象中的key将会作为表头渲染
					let count = 0; //数据总数
					let limit = 3000; //每次请求数量
					//获取总数
					$.ajax({
						type:"post",
						url:"{:url('exportData')}",
						data: {
							m_id:ids
						},
						dataType:"json",
						beforeSend: function () {
							layer.load(1);
						},
						success:function(res){
							layer.closeAll();
							if(res.code == 0) {
								count = res.count;
								if(count == 0) {
									layer.msg('暂无数据可导出');
									return;
								}
								let request_times = Math.ceil(count/limit); //计算分几次请求
								let funcs = []; //Promise.all要用到的参数, 存放每次请求的Promise对象
								let complete_count = 0; //成功请求次数
								let export_percentage = 0; //设置当前进度百分比为0
								for (let i = 1; i <= request_times; i++) {
									// 循环请求次数，构造请求的Promise对象并插入funcs数组
									let func = new Promise(function(resolve, reject){
										//定义Promise并处理请求逻辑
										let data = [];
										$.ajax({
											type:"post",
											url:"{:url('exportData')}?page=" + i,
											data: {
												m_id:ids,
												limit:limit
											},
											dataType:"json",
											success:function(res){
												layer.closeAll();
												if(res.code == 0) {
													data = res.data;
													complete_count++; //成功请求次数+1
													export_percentage = 100*complete_count/request_times; //设置当前进度百分比
													layer.msg('导出中，已完成' + Math.ceil(export_percentage) + '%');
													resolve(data);
												} else {
													layer.msg(res.msg);
													reject();
												}
											}
										});
									});
									funcs.push(func);
								}

								Promise.all(funcs).then(function(values) {
									//使用Promise.all调用funcs里面的函数，并合并数据，最后给js-xlsx生成Excel
									let print_data = [];
									//将数据合并
									for (let i = 0; i < values.length; i++) {
										for (let j = 0; j < values[i].length; j++) {
											print_data.push(values[i][j]);
										}
									}
									// 创建一个新sheet
									const new_sheet = XLSX.utils.json_to_sheet(print_data)
									// 新建book
									const new_book = XLSX.utils.book_new()
									// 将 sheet 添加到 book 中
									XLSX.utils.book_append_sheet(new_book, new_sheet, 'Sheet1')
									// 导出excel文件
									let time = new Date();
									let month = time.getMonth()+1;
									let timeStr = time.getFullYear() + '-' + month + '-'+time.getDate();
									XLSX.writeFile(new_book, '订单列表('+timeStr+').xlsx')
								});

							} else {
								layer.msg(res.msg);
							}
						}
					});
				});
			}
		};

	});
</script>